package com.pingan.cashier.common.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName Md5Encrypt
 * @Description md5签名工具类
 * @Author husheng
 * @Date 2020-01-03 11:33
 */
public class Md5Encrypt {

    private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
            'b', 'c', 'd', 'e', 'f' };

    /**
     * md5签名
     * @param text
     * @return
     */
    public static String md5Sign(String text) {
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }
        //注意改接口是按照指定编码形式签名
        msgDigest.update(text.getBytes(StandardCharsets.UTF_8));
        byte[] bytes = msgDigest.digest();
        return new String(encodeHex(bytes)).toUpperCase();
    }

    private static char[] encodeHex(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS[0x0F & data[i]];
        }
        return out;
    }
}
